<template>
  <view class="container">
    <!-- 用户信息区域 -->
    <view class="user-info">
      <view class="avatar-container">
        <image class="avatar" :src="userInfo.pic || '/static/logo.png'" mode="aspectFill"></image>
      </view>
      <view class="user-details">
        <text class="username">{{ userInfo.userName || '未登录' }}</text>
        <view class="stars" v-if="employeeRating.totalRating">
          <text class="star" v-for="item in 5" :key="item" :class="{ 'filled': item <= Math.floor(employeeRating.totalRating) }">★</text>
          <text class="rating-text">{{ employeeRating.totalRating }}分</text>
        </view>
        <view class="stars" v-else>
          <text class="star" v-for="item in 5" :key="item">★</text>
        </view>
      </view>
    </view>

    <!-- 提成信息 -->
    <view class="commission-section">
      <view class="section-title">提成</view>
      <view class="commission-item">
        <text class="commission-label">总提成：</text>
        <text class="commission-value">¥{{ totalCommission }}</text>
      </view>
      <view class="commission-item">
        <text class="commission-label">提成次数：</text>
        <text class="commission-value">{{ commissionCount }}</text>
      </view>
      <!-- 添加详细提成信息列表 -->
      <view class="commission-details" v-if="commissionDetails.length > 0">
        <view class="detail-item" v-for="(item, index) in commissionDetails" :key="index">
          <text class="detail-title">{{ item.workOrderTitle }}</text>
          <text class="detail-amount">¥{{ item.commissionAmount }}</text>
          <text class="detail-date">{{ item.createTime }}</text>
        </view>
      </view>
      <view class="no-data" v-else>
        <text>暂无提成记录</text>
      </view>
    </view>

    <!-- 工单统计 -->
    <view class="orders-section">
      <view class="section-title">完成工单数</view>
      <view class="orders-count">{{ completedOrders }}</view>
    </view>

    <!-- 星级评价统计 -->
    <view class="rating-section" v-if="employeeRating.evaluationCount > 0">
      <view class="section-title">星级评价</view>
      <view class="rating-stats">
        <view class="rating-row">
          <text class="rating-label">总评分：</text>
          <text class="rating-value">{{ employeeRating.totalRating }}分</text>
        </view>
        <view class="rating-row">
          <text class="rating-label">评价人数：</text>
          <text class="rating-value">{{ employeeRating.evaluationCount }}人</text>
        </view>
        <view class="rating-row">
          <text class="rating-label">五星好评：</text>
          <text class="rating-value">{{ employeeRating.fiveStarCount }}人</text>
        </view>
        <view class="rating-row">
          <text class="rating-label">四星评价：</text>
          <text class="rating-value">{{ employeeRating.fourStarCount }}人</text>
        </view>
      </view>
    </view>

    <!-- 评价 -->
    <view class="rating-section">
      <view class="section-title">评价</view>
      <view class="rating-item" v-for="(rating, index) in displayedRatings" :key="index">
        <view class="rating-header">
          <text class="rating-user">{{ rating.user }}</text>
          <view class="rating-stars">
            <text class="star" v-for="item in 5" :key="item" :class="{ 'filled': item <= rating.score }">★</text>
          </view>
        </view>
        <text class="workorder-id">工单ID: {{ rating.workOrderId }}</text>
        <text class="rating-comment">{{ rating.comment }}</text>
        <text class="rating-time">{{ rating.time }}</text>
      </view>
      
      <!-- 展开/收起按钮 -->
      <view class="toggle-button" v-if="ratings.length > 3" @click="toggleRatings">
        <text class="toggle-text">{{ showAllRatings ? '收起评价' : `展开剩余${ratings.length - 3}条评价` }}</text>
        <text class="arrow" :class="{ 'arrow-up': showAllRatings }">▼</text>
      </view>
    </view>

    <!-- 消息 -->
    <view class="messages-section">
      <view class="section-title">消息</view>
      <view class="message-item" v-for="(message, index) in messages" :key="index" @click="readMessage(message)">
        <view class="message-header">
          <text class="message-title">{{ message.title }}</text>
          <text class="message-time">{{ message.time }}</text>
        </view>
        <text class="message-content">{{ message.content }}</text>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section">
      <button class="logout-button" @click="logout">退出登录</button>
    </view>

    <!-- 添加定时上传位置按钮 -->
    <button class="upload-location-button" @click="startUploadLocation">
      {{ isUploadingLocation ? '停止定时上传位置' : '开始定时上传位置' }}
    </button>
  </view>
</template>

<script>
import { getCompletedOrders } from '../../api/workOrder.js';
import { getEmployeeEvaluation } from '../../api/mine.js';
import { getEmployeeRating } from '../../api/mine.js';
import { getCommissionByEmployeeId } from '../../api/mine.js';

export default {
  data() {
    return {
      totalCommission: 0,
      commissionCount: 0,
      completedOrders: 0,
      userInfo: {
        userName: '',
        pic: ''
      },
      employeeRating: {
        totalRating: 0,
        evaluationCount: 0,
        fiveStarCount: 0,
        fourStarCount: 0
      },
      ratings: [],
      showAllRatings: false, // 控制是否显示所有评价
      messages: [
        {
          title: "系统通知",
          content: "您有新的工单待处理",
          time: "今天 10:30",
          read: false
        },
        {
          title: "活动提醒",
          content: "本月完成50单可获得额外奖励",
          time: "昨天 15:45",
          read: true
        }
      ],
      isUploadingLocation: false,
      uploadInterval: null,
      currentLocation: {
        latitude: '',
        longitude: ''
      },
      // 添加提成详细信息数组
      commissionDetails: [],
    };
  },

  computed: {
    // 计算显示的评价列表
    displayedRatings() {
      if (this.showAllRatings || this.ratings.length <= 3) {
        return this.ratings;
      }
      return this.ratings.slice(0, 3);
    }
  },

  onLoad() {
    this.loadUserInfo();
    this.loadCompletedOrders();
    this.loadRatings();
    this.loadEmployeeRating();
    this.loadCommissionDetails();
  },

  onShow() {
    this.loadUserInfo();
    // 其他数据加载方法只在onLoad中调用一次，避免重复请求
  },

  methods: {
    loadUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          this.userInfo = { ...this.userInfo, ...userInfo };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    // 添加加载员工星级评价的方法
    async loadEmployeeRating() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.id) {
          console.warn('用户未登录或缺少用户ID');
          return;
        }

        const response = await getEmployeeRating(userInfo.id);
        console.log('获取员工星级评价响应:', response);
        
        if (response && response.code === 0 && response.data) {
          // 处理返回的星级评价数据
          this.employeeRating = {
            totalRating: response.data.totalRating || 0,
            evaluationCount: response.data.evaluationCount || 0,
            fiveStarCount: response.data.fiveStarCount || 0,
            fourStarCount: response.data.fourStarCount || 0
          };
        } else if (response && response.code !== 0) {
          console.error('获取员工星级评价失败:', response.msg || '未知错误');
          uni.showToast({
            title: response.msg || '获取星级评价失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载员工星级评价异常:', error);
        uni.showToast({
          title: '加载星级评价异常',
          icon: 'none'
        });
      }
    },

    // 添加加载已完成工单数的方法
    async loadCompletedOrders() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.id) {
          console.warn('用户未登录或缺少用户ID');
          return;
        }

        const params = {
          userId: userInfo.id
        };
        
        const response = await getCompletedOrders(params);
        if (response && response.code === 0) {
          // 假设后端返回的数据是一个数组，数组长度就是完成的工单数
          this.completedOrders = response.data ? response.data.length : 0;
        } else {
          console.error('获取已完成工单失败:', response ? response.msg : '未知错误');
          uni.showToast({
            title: '获取工单数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载已完成工单数异常:', error);
        uni.showToast({
          title: '加载工单数据异常',
          icon: 'none'
        });
      }
    },

    // 添加加载评价信息的方法
    async loadRatings() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.id) {
          console.warn('用户未登录或缺少用户ID');
          return;
        }

        const response = await getEmployeeEvaluation(userInfo.id);
        console.log('获取评价信息响应:', response);
        if (response && response.code === 0 && response.data) {
          // 根据后端返回数据格式处理评价信息
          // 后端返回的是评价列表
          const evaluationList = response.data;
          // 将后端返回的评价数据转换为前端需要的格式
          this.ratings = evaluationList.map(item => {
            return {
              id: item.id,
              workOrderId: item.workOrderId,
              user: "客户",
              score: item.starRating,
              comment: item.content,
              time: item.createTime ? item.createTime.substring(0, 10) : ""
            };
          });
        } else if (response && response.code !== 0) {
          console.error('获取评价信息失败:', response.msg);
          // 当没有评价信息时，清空评价列表
          this.ratings = [];
        }
      } catch (error) {
        console.error('加载评价信息异常:', error);
        // 出现异常时，清空评价列表
        this.ratings = [];
      }
    },

    // 切换评价显示状态
    toggleRatings() {
      this.showAllRatings = !this.showAllRatings;
    },

    async handleLoginResponse(response) {
      const data = response.data;
      if (data.code === 0 && data.data && data.data.sysUserVO) {
        const user = data.data.sysUserVO;

        const userInfo = {
          id: user.id,
          userName: user.userName,
          pic: user.pic || '/static/logo.png',
          phone: user.phone,
          email: user.email,
          token: user.token
        };

        uni.setStorageSync('userInfo', userInfo);
        uni.setStorageSync('token', userInfo.token);

        this.userInfo = userInfo;

        uni.showToast({
          title: `欢迎回来，${userInfo.userName}！`,
          icon: 'success'
        });
      } else {
        uni.showToast({ title: '登录失败', icon: 'none' });
        console.error('登录失败:', data.msg);
      }
    },

    // 添加加载员工提成详情的方法
    async loadCommissionDetails() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.id) {
          console.warn('用户未登录或缺少用户ID');
          return;
        }
        
        const response = await getCommissionByEmployeeId(userInfo.id);
        console.log('获取员工提成详情响应:', response);
        
        if (response && response.code === 0 && response.data) {
          // 处理返回的提成数据
          const data = response.data;
          this.totalCommission = data.totalCommission || 0;
          this.commissionCount = data.commissionCount || 0;
          // 清空详细列表，因为新接口不返回详细信息
          this.commissionDetails = [];
        } else if (response && response.code !== 0) {
          console.error('获取员工提成详情失败:', response.msg || '未知错误');
          uni.showToast({
            title: response.msg || '获取提成详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载员工提成详情异常:', error);
        uni.showToast({
          title: '加载提成详情异常',
          icon: 'none'
        });
      }
    },
    
    readMessage(message) {
      if (!message.read) {
        message.read = true;
        uni.showToast({
          title: '标记为已读',
          icon: 'none'
        });
      }
    },

    goToDetail() {
      uni.navigateTo({
        url: '/pages/mine/minedetail'
      });
    },

    logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('token');
            uni.showToast({ title: '退出成功', icon: 'success' });
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/home/home' });
            }, 1500);
          }
        }
      });
    },

    // 使用 uni.getLocation 获取当前位置（兼容所有平台）
    async getLocation() {
      try {
        // 获取当前位置
        const res = await uni.getLocation({
          type: 'wgs84',
          altitude: true
        });

        const { latitude, longitude } = res;
        console.log('获取到的经纬度:', { latitude, longitude });

        let address = '';
        try {
          // 调用高德地图逆地理编码
          const amapRes = await uni.request({
            url: `https://restapi.amap.com/v3/geocode/regeo?key=59df1612a8aaa186bd6926e8a361e222&location=${longitude},${latitude}`
          });

          console.log('高德逆地理编码响应:', amapRes); // 打印完整响应
          const amapData = amapRes.data;
          // 更详细的日志输出
          console.log('高德API返回数据结构:', amapData);
  
          if (amapData && amapData.status === '1') {
            address = amapData.regeocode.formatted_address;
            console.log('获取到地址:', address);
          } else {
            console.warn('高德API返回错误:', amapData?.info || '未知错误');
          }
        } catch (addrError) {
          console.warn('获取地址信息失败:', addrError);
        }

        return {
          latitude,
          longitude,
          address
        };
      } catch (error) {
        console.error('获取位置失败:', error);
        uni.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
        return null;
      }
    },

    // 上传位置到后端
    async uploadLocation() {
      if (!this.isUploadingLocation) return;

      const location = await this.getLocation();
      if (!location) return;

      const { latitude, longitude, address } = location;
      const employeeId =this.userInfo.id; // 确保已设置
      // 添加调试日志
      console.log('userInfo:', this.userInfo);
      console.log('employeeId:', employeeId);
      console.log('employeeId type:', typeof employeeId);
      console.log('准备上传的位置数据:', {
        employeeId,
        address,
        latitude,
        longitude
      });
      if (!employeeId) {
        uni.showToast({ title: '员工ID缺失', icon: 'none' });
        return;
      }

      const url = 'http://localhost:6001/sys-client/api/employeeAddress/saveOrUpdate';
      const data = {
        employeeId,
        address: address || '',
        latitude: parseFloat(latitude.toFixed(6)),
        longitude: parseFloat(longitude.toFixed(6))
      };

      try {
        const response = await uni.request({
          url,
          method: 'POST',
          data,
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.userInfo.token}` // 添加 token 认证
          }
        });

        console.log('后端响应完整数据:', response); // 打印完整响应
        
  
        const res = response; // 获取实际响应数据
        if (res) {
          console.log('后端响应状态码:', res.statusCode);
          console.log('后端响应数据:', res.data);
          
          if (res.statusCode === 200) {
            const result = res.data;
            if (result && result.code === 0) {
              console.log('位置上传成功');
              uni.showToast({ title: '上传成功', icon: 'success' });
            } else {
              console.error('上传失败:', result?.msg || '未知错误');
              uni.showToast({ title: '上传失败: ' + (result?.msg || '未知错误'), icon: 'none' });
            }
          } else {
            console.error('HTTP 错误:', res.statusCode, res.data);
            uni.showToast({ title: '网络错误: ' + res.statusCode, icon: 'none' });
          }
        } else {
          console.error('请求无响应:', response); // 打印错误信息
          uni.showToast({ title: '请求失败', icon: 'none' });
        }
      } catch (error) {
        console.error('请求异常:', error); // 打印完整错误对象
        console.error('请求异常:', error); // 打印完整错误对象
        uni.showToast({ title: '请求异常', icon: 'none' });
      }
    },

    // 开始/停止定时上传位置
    async startUploadLocation() {
      if (this.isUploadingLocation) {
        clearInterval(this.uploadInterval);
        this.isUploadingLocation = false;
        return;
      }

      // 请求位置权限
      const auth = await uni.getSetting({ key: 'scope.userLocation' });
      if (!auth.authSetting['scope.userLocation']) {
        await uni.authorize({ scope: 'scope.userLocation' });
      }

      this.isUploadingLocation = true;
      this.uploadInterval = setInterval(() => {
        this.uploadLocation();
      }, 60000); // 每分钟上传一次
    },

    // 计算当日和本月提成总额
    calculateCommissions(records) {
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = String(today.getMonth() + 1).padStart(2, '0');
      const currentDay = String(today.getDate()).padStart(2, '0');
      const todayStr = `${currentYear}-${currentMonth}-${currentDay}`;
      
      const firstDayOfMonth = `${currentYear}-${currentMonth}-01`;
      
      let dailyTotal = 0;
      let monthlyTotal = 0;
      
      records.forEach(item => {
        if (item.createTime) {
          // 计算当日提成
          if (item.createTime.startsWith(todayStr)) {
            dailyTotal += item.commissionAmount || 0;
          }
          
          // 计算本月提成
          if (item.createTime >= firstDayOfMonth && item.createTime <= todayStr) {
            monthlyTotal += item.commissionAmount || 0;
          }
        }
      });
      
      this.dailyCommission = dailyTotal;
      this.monthlyCommission = monthlyTotal;
    }
  },

  beforeDestroy() {
    if (this.uploadInterval) {
      clearInterval(this.uploadInterval);
    }
  }
};
</script>

<style>
.container {
  padding: 20rpx;
  padding-top: calc(20rpx + var(--status-bar-height));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  min-height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.user-info {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 40rpx 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.avatar-container {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 30rpx;
}

.avatar {
  width: 100%;
  height: 100%;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.stars {
  display: flex;
  align-items: center;
}

.star {
  font-size: 36rpx;
  color: #ddd;
}

.star:first-child {
  margin-left: 0;
}

.star.filled {
  color: #ffcc00;
}

.rating-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.edit-button {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007AFF;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
}

.edit-text {
  color: #fff;
  font-size: 24rpx;
}

.status-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.status-item {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.status-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 20rpx;
}

.commission-section,
.orders-section,
.rating-section,
.messages-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.commission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.commission-label {
  font-size: 28rpx;
  color: #666;
}

.commission-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4d4f;
}

/* 添加提成详情样式 */
.commission-details {
  margin-top: 20rpx;
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-title {
  font-size: 26rpx;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-amount {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff4d4f;
  margin: 0 20rpx;
}

.detail-date {
  font-size: 24rpx;
  color: #999;
}

.no-data {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
}

.orders-count {
  font-size: 48rpx;
  font-weight: bold;
  color: #007AFF;
  text-align: center;
}

.rating-stats {
  padding: 10rpx 0;
}

.rating-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.rating-row:last-child {
  margin-bottom: 0;
}

.rating-label {
  font-size: 28rpx;
  color: #666;
}

.rating-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.rating-item {
  margin-bottom: 30rpx;
}

.rating-item:last-child {
  margin-bottom: 0;
}

.rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.rating-user {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.rating-stars {
  display: flex;
}

.star {
  font-size: 24rpx;
  color: #ddd;
}

.star.filled {
  color: #ffcc00;
}

.rating-comment {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.workorder-id {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
  font-family: monospace;
}

.rating-time {
  font-size: 24rpx;
  color: #999;
}

.message-item {
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.message-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.message-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.message-time {
  font-size: 24rpx;
  color: #999;
}

.message-content {
  font-size: 26rpx;
  color: #666;
}

.logout-section {
  padding: 20rpx 0;
}

.logout-button {
  background-color: #ff4d4f;
  color: #fff;
  border: none;
  padding: 40rpx 0;
  border-radius: 10rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.logout-button:active {
  background-color: #cc3333;
}

.toggle-button {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  margin-top: 20rpx;
  color: #007AFF;
}

.toggle-text {
  font-size: 28rpx;
}

.arrow {
  margin-left: 10rpx;
  transition: transform 0.3s ease;
}

.arrow-up {
  transform: rotate(180deg);
}
</style>